<template>
  <div class="_race" :class="{ _mobile: isMobile }">
    <div class="_race-time">
      <div class="_race-time-inner">
        <img class="_race-left _race-img" :src="LeftRace" />
        <div class="_time">
          <div class="_price">
            Weekly race {{ weeklyReward ? `$${weeklyReward}` : "-" }}
          </div>
          <div class="_time-wrapper">Race Ends in {{ secondText || "-" }}</div>
        </div>
        <img class="_race-right _race-img" :src="RightRace" />
      </div>
    </div>
    <div class="_rank">
      <img :src="BoxBg" class="_rank-bg" />
      <div
        class="_rank-item"
        :class="{ [`_rank-${item.rank}`]: true }"
        v-for="item in rankTops"
        :key="item.rank"
      >
        <div class="_rank-header">
          <img :src="item.icon" />
          <span class="_rank-name">{{ item.iconName }}</span>
        </div>
        <template v-if="!loading">
          <div class="_rank-user-info">
            <div class="_head">
              <img :src="item.user?.head_image" />
            </div>
            <div class="_rank-username">{{ item.user?.user_name }}</div>
            <div class="_rank-amount">
              <span>$</span>
              <span>{{ item.user?.reward_amount }}</span>
            </div>
          </div>
          <div class="_rank-footer">
            <div>Opened</div>
            <div>
              <span>$</span>
              <span>{{ item.user?.open_amount }}</span>
            </div>
          </div>
        </template>
        <template v-else>
          <div class="_rank-loading">
            <loading-comp class="!w-2.5rem" :track-width="6" />
          </div>
        </template>
      </div>
    </div>
    <div class="_table">
      <el-table size="large" :data="tableRanks">
        <el-table-column
          label="#"
          prop="rank_sort"
          align="center"
          v-bind="isMobile ? { width: '42px' } : { width: '50px' }"
        >
          <template #default="{ row }">
            <span
              :class="{ '_text-middle': !isMobile, 'text-0.75rem': isMobile }"
            >
              {{ row.rank_sort }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="Leaderboard"
          v-bind="isMobile ? { width: '122px' } : {}"
        >
          <template #default="{ row }">
            <div class="_leader-board">
              <img :src="row.head_image" />
              <span class="flex-1 w-0 _text-ellipsis">{{ row.user_name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="Opened" prop="open_amount" align="center">
          <template #default="{ row }">
            <span
              class="!text-hex-fff"
              :class="{ '_text-middle': !isMobile, '_text-small': isMobile }"
            >
              {{ row.open_amount }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="Reward" :align="isMobile ? 'center' : 'right'">
          <template #default="{ row }">
            <div
              class="text-primary"
              :class="{ '_text-middle': !isMobile, '_text-small': isMobile }"
            >
              <span>$</span>
              <span>{{ row.reward_amount }}</span>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script lang="tsx" setup>
import { getRace } from "@/api/events";
import BoxBg from "@/assets/box-bg.png";
import LeftRace from "@/assets/left-race.png";
import Rank1 from "@/assets/rank1.png";
import Rank2 from "@/assets/rank2.png";
import Rank3 from "@/assets/rank3.png";
import RightRace from "@/assets/right-race.png";
import LoadingComp from "@/components/Loading/loading.vue";
import { useMedia } from "@/hooks/useMedia";

const ranks = ref<API.Race.RankUserItem[]>([]);
const loading = ref(false);
const isMobile = useMedia();
const weeklyReward = ref("");
const endSeconds = ref(0);
const timer = ref(0);

const rankTops = computed(() => {
  return [
    {
      rank: 2,
      icon: Rank2,
      iconName: "2nd Place",
      user: ranks.value?.[2],
    },
    {
      rank: 1,
      icon: Rank1,
      iconName: "1st Place",
      user: ranks.value?.[1],
    },
    {
      rank: 3,
      icon: Rank3,
      iconName: "2rd Place",
      user: ranks.value?.[3],
    },
  ];
});

const tableRanks = computed(() => {
  return ranks.value.length > 3 ? ranks.value.slice(3) : [];
});

const secondText = computed(() => {
  if (endSeconds.value === 0) {
    return "";
  }

  const hours = Math.floor(endSeconds.value / 3600);
  const minutes = Math.floor((endSeconds.value % 3600) / 60);
  const seconds = Math.floor((endSeconds.value % 3600) % 60);
  if (hours > 0) {
    return `${hours}H ${minutes}M ${seconds}S`;
  }

  if (minutes > 0) {
    return `${minutes}M ${seconds}S`;
  }

  return `${seconds}S`;
});

async function startTime() {
  if (endSeconds.value === 0) {
    await new Promise((resolve) => setTimeout(resolve, 1000));
    return getRaceInfo();
  }
  window.clearTimeout(timer.value);
  timer.value = window.setTimeout(() => {
    endSeconds.value = endSeconds.value - 1;
    startTime();
  }, 1000);
}

async function reRaceInfo() {
  startTime();
  await new Promise((resolve) => window.setTimeout(resolve, 60 * 1000));
  getRaceInfo();
}

async function getRaceInfo() {
  const result = await getRace();
  ranks.value = result?.rank_list || [];
  weeklyReward.value = result?.weekly_reward || "";
  endSeconds.value = result?.end_seconds;
  reRaceInfo();
}

onBeforeMount(async () => {
  loading.value = true;
  await getRaceInfo();
  loading.value = false;
});

onBeforeUnmount(() => {
  window.clearTimeout(timer.value);
});
</script>

<style lang="less" scoped>
._race {
  ._race-time {
    padding: 2.06rem 2.75rem;
    height: 16rem;
    background-color: #232829;
    border-radius: 0.5rem;
    ._race-time-inner {
      @apply flex items-center justify-between w-full h-full;
      background-color: #1a1b1c;
      img {
        height: 100%;
        object-fit: contain;
      }

      ._time {
        @apply flex-1 w-0 flex flex-col items-center;
        gap: 2rem;
        ._price {
          font-size: 1.88rem;
          color: #ffffff;
          line-height: 2.13rem;
          text-align: left;
        }
        ._time-wrapper {
          @apply flex items-center justify-center;
          width: 18.94rem;
          height: 2.5rem;
          font-size: 1.13rem;
          border-radius: 0.63rem;
          border: 0.06rem solid #353636;
          border-radius: 0.63rem;
        }
      }
    }
  }

  ._rank {
    @apply relative flex items-stretch justify-center;
    padding: 5.25rem 0 2.5rem;
    gap: 2.13rem;
    ._rank-bg {
      @apply absolute top-0;
      height: 100%;
      object-fit: contain;
    }

    ._rank-item {
      @apply relative flex flex-col justify-between;
      z-index: 1;
      width: 11.88rem;
      aspect-ratio: 11.88 / 15.81;
      min-height: 0;
      background-color: #232829;
      border-radius: var(--el-border-radius-base);
      overflow: hidden;
      &._rank-1 {
        @apply relative;
        top: -2.63rem;
      }

      ._rank-header {
        @apply relative flex items-center justify-center;
        img {
          width: 5.81rem;
          object-fit: contain;
        }

        ._rank-name {
          @apply absolute;
          top: 0;
          left: 50%;
          transform: translateX(-50%);
          padding-top: 0.15rem;
          font-size: 1rem;
        }
      }

      ._rank-loading {
        @apply flex-1 flex items-center justify-center;
      }

      ._rank-user-info {
        @apply flex-1 flex flex-col items-center justify-start;
        margin-top: 0.94rem;
        ._head {
          width: 3.38rem;
          aspect-ratio: 1/1;
          img {
            width: 100%;
            height: 100%;
            object-fit: contain;
          }
        }
        ._rank-username {
          margin: 1rem 0 0.88rem;
          color: #9d9d9d;
          font-size: 0.88rem;
        }
        ._rank-amount {
          font-size: 1.13rem;
          line-height: 1.31rem;
        }
      }

      ._rank-footer {
        @apply flex flex-col items-center justify-center;
        height: 3.25rem;
        color: #9d9d9d;
        font-size: 0.88rem;
        line-height: 1.31rem;
        background-color: #353636;
      }
    }
  }

  ._table {
    background: #232829;
    border-radius: 0.5rem;
  }

  ._leader-board {
    @apply flex items-center;
    gap: 0.8rem;
    img {
      width: 2rem;
      object-fit: contain;
    }
  }

  &._mobile {
    ._race-time {
      position: relative;
      padding: 0.94rem;
      aspect-ratio: unset;
      height: auto;
      min-height: auto;
      ._race-time-inner {
        padding: 1.88rem 3.44rem;
        border-radius: 0.5rem;
        ._time {
          position: relative;
          z-index: 1;
          gap: 0.75rem;
          width: 100%;
          ._price {
            font-size: 0.88rem;
          }
          ._time-wrapper {
            width: 100%;
            height: 2.13rem;
            font-size: 0.75rem;
            border-radius: 0.63rem;
            background-color: #1a1b1c;
          }
        }

        ._race-img {
          @apply absolute;
          width: 6.21rem;
          height: 5.31rem;
          left: 0.31rem;
          top: 0.63rem;
          &._race-right {
            left: unset;
            right: 0.31rem;
          }
        }
      }
    }

    ._rank {
      padding: 4.75rem 0.94rem 1.69rem;
      gap: 0.5rem;

      ._rank-item {
        overflow: visible;
        &._rank-1 {
          top: -1.19rem;
        }
      }

      ._rank-header {
        position: relative;
        top: -0.2rem;

        img {
          width: 3.15rem;
        }
        ._rank-name {
          font-size: 0.56rem;
        }
      }

      ._rank-loading {
        @apply flex-1 flex items-center justify-center;
      }

      ._rank-user-info {
        @apply flex-1 flex flex-col items-center justify-start;
        margin-top: 0.1rem;
        ._head {
          width: 2rem;
        }
        ._rank-username {
          margin: 0.56rem 0 0.42rem;
          font-size: 0.63rem;
        }
        ._rank-amount {
          font-size: 0.69rem;
          line-height: 0.75rem;
        }
      }

      ._rank-footer {
        height: 2.19rem;
        font-size: 0.56rem;
        line-height: 0.71rem;
        border-radius: 0 0 var(--el-border-radius-base)
          var(--el-border-radius-base);
      }
    }
  }
}
</style>

<style lang="less">
._race {
  &._mobile {
    .el-table--large {
      .cell {
        padding: 0 0.4rem;
      }
    }
  }
}
</style>
